package com.example.demo.ExcelTest;

import com.alibaba.fastjson.JSONArray;
import com.example.demo.ExcelTest.entity.StandingBook;
import com.example.demo.ExcelTest.entity.User;
import com.example.demo.ExcelTest.util.ExcelUtils;
import com.google.common.base.Objects;
import org.apache.poi.poifs.filesystem.FileMagic;
import org.apache.tika.Tika;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author FF998
 */
@RestController
@RequestMapping("/excelTest")
public class ExcelSetTest {

    private static final String UPLOAD_DIR = "AAA";

    @PostMapping("/import")
    public JSONArray importExcel(@RequestPart("file") MultipartFile file) throws Exception {
        List<User> users = ExcelUtils.readMultipartFile(file, User.class);
        users.forEach(System.out::println);
        return null;
    }

    @PostMapping(value = "/import/standingBook", name = "Excel导入")
    public JSONArray importStandingBook(@RequestPart("file") MultipartFile file) throws Exception {
        List<StandingBook> users = ExcelUtils.readMultipartFile(file, StandingBook.class);
        List<StandingBook> collect = users.stream().filter(x -> !"小计".equals(x.getDistrictCode())).collect(Collectors.toList());
        collect.forEach(System.out::println);
        return null;
    }

    @GetMapping(value = "/export", name = "导出Excel模版")
    public void export(HttpServletResponse response) {
        ExcelUtils.exportTemplate(response, "导入模板", StandingBook.class, true);
    }

    @PostMapping(value = "/api/upload", name = "上传文件校验")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        // 文件类型校验
        String contentType = file.getContentType();
        if (!contentType.equals("image/jpeg") && !contentType.equals("image/png") && !contentType.equals("application/pdf")) {
            return "文件类型不符合要求！";
        }

        // 流方式校验每一行数据
//        try (BufferedReader br = new BufferedReader(new InputStreamReader(file.getInputStream()))) {
//            String line;
//            while ((line = br.readLine()) != null) {
//                // 检查是否包含可疑脚本
//                if (line.contains("<script>") || line.contains("eval(")) {
//                    return "上传被拒绝：文件包含可疑脚本。";
//                }
//            }
//            System.out.println("文件上传成功。");
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "文件内容校验失败！";
//        }

        // 文件头信息校验
        try {
            InputStream inputStream = file.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            // 获取到上传文件的文件头信息
            boolean isExcel = checkIsExcel(bufferedInputStream);
            if (!isExcel) {
                throw new RuntimeException("文件类型不正确");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

//        // 文件内容校验
//        try {
//
//            Tika tika = new Tika();
//            String mimeType = tika.detect(file.getInputStream());
//            System.out.println(mimeType);
////            if ( mimeType.equals("application/pdf") || mimeType.startsWith("image/")){
////                return "文件类型不符合要求！";
////            }
//            // 对文件内容进行校验操作
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "文件内容校验失败！";
//        }

        // 指定上传路径
        String uploadDir = "D:/upload_files/test/";
        // 检查上传目录是否存在
        File directory = new File(uploadDir);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录
        }

        // 文件路径
        String filePath = uploadDir + file.getOriginalFilename();

        // 保存文件
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(file.getBytes());
            return "文件上传成功: " + filePath;
        } catch (IOException e) {
            e.printStackTrace();
            return "文件上传失败: " + e.getMessage();
        }
    }

    private static boolean checkIsExcel(InputStream inputStream) throws IOException {
        //获取文件流的文件头
        FileMagic fileMagic = FileMagic.valueOf(inputStream);
        //判断Excel文件头是否符合xls或者xlsx
        if (Objects.equal(fileMagic, FileMagic.PDF) || Objects.equal(fileMagic, FileMagic.OOXML)) {
            return true;
        }
        return false;
    }

}
